package cn.tedu.straw.search.schedule;

import cn.tedu.straw.search.repository.QuestionRepository;
import cn.tedu.straw.search.service.IQuestionService;
import cn.tedu.straw.search.vo.QuestionVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class LoadQuestionsSchedule {

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private QuestionRepository questionRepository;

    @Scheduled(fixedRate = 10*60*1000)
    public void loadQuestion(){
        // 清空当前ElasticSearch服务器中所有"问题"文档：直接将整个索引删除
        elasticsearchOperations.indexOps(QuestionVO.class).delete();
        // 循环读取MySQL数据库中的数据，并将数据写入到ElasticSearch服务器中
        int pageNum = 1;
        PageInfo<QuestionVO> pageInfo= null;
        do {
            // 读取MySQL数据库中的数据
            pageInfo = questionService.getQuestionsFromDataBase(pageNum);
            // 页面自增
            pageNum++;
            // 将读取到的数据全部写入到ElasticSearch服务器中
            questionRepository.saveAll(pageInfo.getList());
        }while (pageInfo.isHasNextPage());
    }
}
